package com.brian.mongo.service;

import com.brian.mongo.annotation.BrianCache;
import com.brian.mongo.domain.User;
import com.brian.mongo.exception.UserAlreadyExistException;
import com.brian.mongo.exception.UserNotFoundException;
import com.brian.mongo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

/**
 * @program: architect
 * @author: Brian Huang
 * @create: 2019-05-16 11:02
 **/

@Service
public class UserService {

    private UserRepository userRepository;

    @Autowired
    private RedisService redisService;

    @Autowired
    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public List<User> getUserByName(String username) throws UserNotFoundException {
        List<User> userList = userRepository.findUserByUsername(username);
        return userList;
    }

    @BrianCache
    public User getUserById(String id) throws UserNotFoundException {
        Optional<User> user = userRepository.findById(id);
        if(user.isPresent()){
            return user.get();
        }
        return null;
    }

    public List<User> getAllUsers(){
        return userRepository.findAll();
    }

    public boolean validateUser(String username, String password) throws UserNotFoundException {
        User user = userRepository.validateUser(username, password);
        if(user != null) {
            return true;
        }else{
            return false;
        }
    }

   @Transactional
    public User saveUser(User user) throws UserAlreadyExistException {

        Optional<User> ouser = userRepository.findById(user.getId());
        if(ouser.isPresent()){
            throw new UserAlreadyExistException();
        }
        //user.setId(String.valueOf(System.currentTimeMillis()));

        redisService.setString(user.getId(),user.toString());

        User save = userRepository.save(user);

        return save;
    }

}
